import React, { Component, Fragment } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { actionCreators } from './store';
import { inputConfig } from '../inputConfig';

import { Modal, Input, Button, Steps, Form, Select, Checkbox } from 'antd';

const { Step } = Steps;
const { Option } = Select;

class TableInput extends Component{
  state={
    visible: false,
    indeterminate: true,
    checkAll: false,
  }

  handleClick = () => {
    this.setState({visible:true})
  };

  handleOk = () => {
    this.props.formRef.current.setFieldsValue({name:this.props.inputCheckList.length>0?this.props.inputCheckList:undefined});
    this.setState({visible:false});
  }

  handleCancel = () => {
    this.setState({visible:false});
  }

  selectConfig = value => {//改变数据库连接
    let config = JSON.parse(value);
    this.props.setConfig(config);
    console.log("数据库连接信息",config);
    this.props.addOriConfig(this.props.taskId,config.databaseId);
    this.props.getOriginTable(config.databaseType,{id:config.databaseId});
    this.props.clearField();
    this.props.setInputCheckList([]);
    this.props.formRef.current.setFieldsValue({oriTable:undefined, name:undefined, columnFamily:undefined});
  }

  onFieldChange = checkedList => {
    this.props.setInputCheckList(checkedList);
    this.setState({
      indeterminate: !!checkedList.length && checkedList.length < this.props.column.length,
      checkAll: checkedList.length === this.props.column.length,
    });
  };

  onCheckAllChange = e => {
    this.props.setInputCheckList(e.target.checked ? this.props.column : []);
    this.setState({
      indeterminate: false,
      checkAll: e.target.checked,
    });
  };

  handleTableChange = (value) => {
    let dbType = this.props.config.databaseType;
    let id = this.props.config.databaseId;
    let table = value;
    this.props.formRef.current.setFieldsValue({name:undefined});
    this.props.setInputCheckList([]);
    this.props.getColumns(dbType,{id,table})//mysql、sqlsever、MongoDB、oracle为表->列，hbase为列族->列
  }

  handleHBaseTableChange = (value) => {//选择hbase表后查找列族
    let id = this.props.config.databaseId;
    let table = value;
    this.props.formRef.current.setFieldsValue({columnFamily:undefined, name:undefined});
    this.props.setInputCheckList([]);
    this.props.getColumnFamily(id,table);
  }

  renderFormItem = (item) => {//根据不同的数据库连接渲染不同的表输入表单项
    let func = this[`${item.function}`];
    let message = item.message?item.message:"";
    switch(item.type){
      case 'select':
        return <Form.Item label={item.label} name={item.name}
        rules={[{
          required: true,
          message: {message},
        },]}>
          <Select placeholder={item.placeholder} onChange={func}
          showSearch
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }>
            {
              this.props.oriTable.map(table => (
                <Option value={table}>{table}</Option>
              ))
            }
          </Select>
        </Form.Item>
      case 'selectColumnFamily':
        return <Form.Item label={item.label} name={item.name}
        rules={[{
          required: true,
          message: {message},
        },]}>
          <Select placeholder={item.placeholder} onChange={func}
          showSearch
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }>
            {
              this.props.columnFamily.map(columnFamily => (
                <Option value={columnFamily}>{columnFamily}</Option>
              ))
            }
          </Select>
        </Form.Item>
      case 'fieldSelect': 
        return <Fragment>
          <Form.Item label="字段选择" name="name"
          rules={[{
            required: true,
            message: '请进行字段选择！',
          },]}>
            <Button type="dashed" onClick={this.handleClick}>字段选择</Button>
          </Form.Item>
          <Modal
            title="字段选择"
            visible={ this.state.visible }
            onOk={ this.handleOk }
            onCancel={ this.handleCancel }
          >
            <div style={{ borderBottom: '1px solid #E9E9E9' }}>
              <Checkbox
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
              >
                全选
              </Checkbox>
            </div>
            <br />
            <Form.Item>
              <Checkbox.Group
                options={this.props.column}
                value={this.props.inputCheckList}
                onChange={this.onFieldChange}
              />
            </Form.Item>
          </Modal>
        </Fragment>
      default: return null;
    }
  }

  render(){
    return (
      <Fragment>
        <Form.Item label="数据库连接" name="originConfig"
        rules={[{
          required: true,
          message: '请选择数据库连接！',
        },]}>
          <Select placeholder="请选择数据库连接" onChange={this.selectConfig}>
            {
              this.props.briefConfig.map(config => (
                <Option key={config.id} value={JSON.stringify(config)}>{config.configName}</Option>
              ))
            }
          </Select>
        </Form.Item>
        {
          this.props.config?
          inputConfig(this.props.config.databaseType).formSourceMapping.map(item=>{//inputConfig(databaseType)匹配不同数据库类型对应的表单项
            return this.renderFormItem(item);
          }):null
        }
      </Fragment>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    briefConfig: state.getIn(['createTask','briefConfig']).toJS(),
    oriTable: state.getIn(['createTask','oriTable']).toJS(),
    columnFamily: state.getIn(['createTask','columnFamily']).toJS(),
    column: state.getIn(['createTask','column']).toJS(),
    taskId: state.getIn(['createTask','taskId']),
  }
}

const mapDispatchToProps = (dispatch) => ({
  getOriginTable(databaseType,params){
    dispatch(actionCreators.getOriginTableOperation(databaseType,params));
  },
  getColumns(dbType,params){
    dispatch(actionCreators.getColumnsOperation(dbType,params));
  },
  getColumnFamily(id,database){
    dispatch(actionCreators.getColumnFamilyOperation(id,database));
  },
  clearField(){
    dispatch(actionCreators.clearFieldOperation());
  },
  addOriConfig(taskId,databaseId){
    dispatch(actionCreators.addOriConfigOperation(taskId,databaseId));
  },
})

export default connect(mapStateToProps, mapDispatchToProps)(TableInput);